<?php
$isReloadable = false;
require_once("../../../pers/inc.config.php");
require_once('../../_inc/inc.session.php');
require_once('../../_inc/funct.html.php');
require_once('../../_inc/funct.tabDati.php');

$aExp = array();
if (reqVar('azione')=='upload')  {
	$msgPag .= uploadSetdati($aExp);
}
if (reqVar('azione')=='crea' || reqVar('azione')=='sost')  {
	$msgPag .= importSetdati($aExp, $aSetdati);
}

$cmdL = "";


$cmdR = '';
if (reqVar('file_caricato')!='') { 
	$cmdR .= "&nbsp;&nbsp;&nbsp;";
	$cmdR .= "<a class=\"cmd1\" href=\"javascript:submAz('sost');\">sostituisci esistente</a>";
		$cmdR .= "&nbsp;&nbsp;&nbsp;";
	$cmdR .= "<a class=\"cmd1\" href=\"javascript:submAz('crea');\">crea nuovo</a>";
}
$cmdR .= cmdTorna(); 
testaHtml('Gestione modelli',  $msgPag, 'modl');
echo getHtmlForm();
echo getHtmlHidden('xsn',XSN);
echo getHtmlHidden('azione','...');
echo getHtmlHidden('file_caricato');
echo getHtmlHidden('file_orig');
?>
<script language="JavaScript" type="text/javascript">
  	function submAz(az) {
  		document.frm1.azione.value = az;
  		document.frm1.submit();
  	}
</script>
<table class="cmd1" border="0" cellpadding="3" cellspacing="1" width="100%">
   <tr>
      <td class="cmd1" align="left">
         <?=$cmdL?>
      </td>
      <td class="cmd1" align="right">
         <?=$cmdR?>
      </td>
   </tr>
</table>
<table class="tab1" border="0" cellpadding="3" cellspacing="1" width="100%">
   <tr>
      <td class="tit1" colspan='2'>Importazione Set Dati</td>
   </tr>
   <tr>
      <td class="lab1" colspan='1' align='left'>File setDati_xxx.ser</td>
      <td class="txt1" colspan='1' align='left'>
<?
echo getHtmlFile('file_ser', 80);
echo "&nbsp;&nbsp;&nbsp;";
if (reqVar('file_caricato')=='') { 
	echo "<a class=\"cmd1\" href=\"javascript:submAz('upload');\">upload</a>";
} else {
	echo "<a class=\"cmd1\" href=\"javascript:submAz('upload');\">nuovo upload</a>";
}
?>
      </td>
   </tr>
   <tr>
      <td class="lab1" colspan='1'  width='20%'>File caricato</td>
      <td class="txt1" colspan='1'  width='80%'>
      	<?=reqVar('file_orig');?>
      </td>
   </tr>
<?
if (is_array($aExp) && count($aExp) > 0) {
?>
   <tr>
      <td class="lab1" colspan='1'>Data export</td>
		<td class="txt1" colspan='1'><?=date('d/m/y H:i',$aExp['head']['data_ora'])?></td>
	</tr>
   <tr>
      <td class="lab1" colspan='1'>Servert</td>
		<td class="txt1" colspan='1'><?=$aExp['head']['server']?></td>
	</tr>
   <tr>
      <td class="lab1" colspan='1'>Data base</td>
		<td class="txt1" colspan='1'><?=$aExp['head']['data_base']?></td>
	</tr>
   <tr>
      <td class="lab1" colspan='1'>Cod. orig</td>
		<td class="txt1" colspan='1'>
			<?=$aExp['body']['rec']['cod_set_dati'].' - '.$aExp['body']['rec']['descr']?>
		</td>
	</tr>
	<tr>
		<td class="lab1">Nuovo codice</td>
		<td class="txt1">
   		<?echo getHtmlText('new_cod',16);?>
		</td>
	</tr>
<?
}
?>
</table>
<table class="cmd1" border="0" cellpadding="3" cellspacing="1" width="100%">
   <tr>
      <td class="cmd1" align="left">
         <?=$cmdL?>
      </td>
      <td class="cmd1" align="right">
         <?=$cmdR?>
      </td>
   </tr>
</table>
<?
echo "</form>\n";
codaHtml();
exit();

function importSetdati(&$aExp, $aSetdati) {
	global $objDB, $objSess;
	$msg = '';
	$aExp = unserialize(gzuncompress(file_get_contents(RGL_FS_TEMP_DIR."/".reqVar('file_caricato'))));
	if (!is_array($aExp)
	|| !isset($aExp['head'])
	|| !isset($aExp['head']['tipo'])) {
		$_REQUEST['file_caricato'] = '';
		return "file non conforme o corrotto<br>";
	}
	if ($aExp['head']['tipo'] != 'setDati') {
		$_REQUEST['file_caricato'] = '';
		return "file importazione '".$aExp['head']['tipo']."' - atteso 'setrdati'<br>";
	}
	if (reqVarTrim('new_cod') == '') {
		$_REQUEST['new_cod'] = $aExp['body']['rec']['cod_set_dati'];
	}
	$_REQUEST['new_cod'] = strtoupper(reqVarTrim('new_cod'));
	$newCod = reqVar('new_cod');
	
	if (preg_match("/[^_A-Z0-9]/",$newCod)) {
		$msg .= _t("Codice '%s' puo' contenere solo lettere numeri e '-'",$newCod)."<br>";
	}
	$sSql = "SELECT id_set_dati FROM rgl_set_dati WHERE cod_set_dati = '".addslashes($newCod)."'";
	$objDB->query($sSql);
	$idSetdati = 0;
	if ($aX=$objDB->fetch()) { //new_cod esistente
		$idSetdati = $aX['id_set_dati'];
		if (reqVar('azione')=='crea') {
			$msg .= "Codice esistente<br>";
		}
	} else {//new_cod inesistente
		if (reqVar('azione')=='sost') {
			$msg .= "Codice inesistente<br>";
		}		
	}
	if ($msg!='') return $msg;
	
	if (reqVar('azione')=='crea') {
		$sSql = 'INSERT INTO rgl_set_dati SET ';
		foreach($aExp['body']['rec'] as $nC => $vC) {
			if ($nC=='id_set_dati') continue;
			if ($nC=='cod_set_dati') {
				$vC =  $newCod;
			}
			$sSql .= $nC." = '".addslashes($vC)."', ";
		}
		$sSql = substr($sSql,0,-2);
		$objDB->exec($sSql);
		$idSetdati = $objDB->lastInsertId();
		foreach($aExp['body']['dati'] as $kX => $aX) {
			$sSql = 'INSERT INTO rgl_def_dato SET ';
			foreach($aX as $nC => $vC) {
				if ($nC=='id_set_dati') {
					$vC =  $idSetdati;
				}
				$sSql .= $nC." = '".addslashes($vC)."', ";
			}
			$sSql = substr($sSql,0,-2);
			$objDB->exec($sSql);	
		}
		return 'creato set dati.'.$newCod.'<br>';
	}
	if (reqVar('azione')=='sost') {
		$sSql = 'UPDATE rgl_set_dati SET ';
		foreach($aExp['body']['rec'] as $nC => $vC) {
			if ($nC=='id_set_dati') continue;
			if ($nC=='cod_set_dati') continue;
			$sSql .= $nC." = '".addslashes($vC)."', ";
		}
		$sSql = substr($sSql,0,-2)." WHERE id_set_dati = $idSetdati ";
		$objDB->exec($sSql);
		$aDatiImp = array();
		foreach($aExp['body']['dati'] as $kX => $aX) {
			$aDatiImp[] = $aX['cod_dato'];
			$sSql = "SELECT cod_dato FROM rgl_def_dato "
				." WHERE id_set_dati = $idSetdati "
				."    AND cod_dato = '".$aX['cod_dato']."'";
			$objDB->query($sSql);
			if ($acDA=$objDB->fetch()) {
				$sSql = 'UPDATE rgl_def_dato SET ';
				foreach($aX as $nC => $vC) {
					if ($nC=='id_set_dati') continue;
					if ($nC=='cod_dato') continue;
					$sSql .= $nC." = '".addslashes($vC)."', ";
				}
				$sSql = substr($sSql,0,-2)." WHERE id_set_dati = $idSetdati "
					."    AND cod_dato = '".$aY['cod_dato']."'";
				$objDB->exec($sSql);	
			} else {
				$sSql = 'INSERT INTO rgl_def_dato SET ';
				foreach($aX as $nC => $vC) {
					if ($nC=='id_set_dati') {
						$vC =  $idSetdati;
					}
					if ($nC=='id_def_tdati') {
						$vC =  $idDefTdati;
					}
					$sSql .= $nC." = '".addslashes($vC)."', ";
				}
				$sSql = substr($sSql,0,-2);
				$objDB->exec($sSql);	
			}
		}
		// eliminazione dati non piu' presenti
		$sSql = "SELECT cod_dato FROM rgl_def_dato "
			." WHERE id_set_dati = $idSetdati ";
		$objDB->query($sSql,'selDati');
		while ($acDA=$objDB->fetch('selDati')) {
			if (!in_array($acDA['cod_dato'],$aDatiImp)) {
				$sSql = "DELETE FROM rgl_def_dato "
					." WHERE id_set_dati = $idSetdati "
					." AND cod_dato = '".$acDA['cod_dato']."'";
				$objDB->query($sSql,'delDato');				
			}
		}
		return 'sostituito set dati.'.$newCod.'<br>';
	}
	return "???";
}

function uploadSetdati(&$aExp) {
	global $objDB, $objSess;
	$aExp = array();
	if (!isset($_FILES['file_ser']) || $_FILES['file_ser']['tmp_name'] == '') {
		$_REQUEST['file_caricato'] = '';
		$_REQUEST['file_orig'] = '';
		return "nessun file caricato<br>";
	}
	$dh = opendir(RGL_FS_TEMP_DIR);
	while($fn = readdir($dh)) {
		if (substr($fn,0,15)=='setDati_import_'
		&& filemtime(RGL_FS_TEMP_DIR."/".$fn) < (time()-3600*24)) {
			unlink(RGL_FS_TEMP_DIR."/".$fn);
		}
	}
	$_REQUEST['file_orig'] = $_FILES['file_ser']['name'];
	$aExp = unserialize(gzuncompress(file_get_contents($_FILES['file_ser']['tmp_name'])));
	if (!is_array($aExp)
	|| !isset($aExp['head'])
	|| !isset($aExp['head']['tipo'])) {
		$_REQUEST['file_caricato'] = '';
		return "file non conforme o corrotto<br>";
	}
	if ($aExp['head']['tipo'] != 'setDati') {
		$_REQUEST['file_caricato'] = '';
		return "file importazione '".$aExp['head']['tipo']."' - atteso 'setDati'<br>";
	}
	$fileCar = "setDati_import_".uniqid();
	$pathFileCar = RGL_FS_TEMP_DIR."/".$fileCar;
	copy($_FILES['file_ser']['tmp_name'],$pathFileCar);
	$_REQUEST['file_caricato'] = $fileCar;
	$_REQUEST['file_orig'] = $_FILES['file_ser']['name'];
	return "file caricato<br>";
}
